package com.yx.frame.authority;

import org.json.JSONArray;

import com.yx.frame.server.Application;
import com.yx.frame.service.ServiceError;

public final class AuthorityManager {
	public static final String PUBLIC_KEY="ShhOt0m5gfMpsLjP";
	static AuthorityManager instance = null;
	private int USER_TIMEOUT = 1200000;
	private long timeDifference=-1;

	private AuthorityManager() {
	}

	public static AuthorityManager getInstance() {
		if (instance == null) {
			instance = new AuthorityManager();
		}
		return instance;
	}
	public long getTimeDifference() {
		return timeDifference;
	}

	public void setTimeDifference(long timeDifference) {
		this.timeDifference = timeDifference;
	}
	public User authentication(String uId,ServiceError error)throws Exception{
		try {
			String signTxt = EncryptTools.AESDecrypt(uId, PUBLIC_KEY);
			JSONArray signArray=new JSONArray(signTxt);
			String userName=signArray.getString(0);
			String ciphertext=signArray.getString(1);
			//String timestmp=signArray.getString(2);	
			String timestmp = signArray.get(2).toString();
			if(timeDifference>0){
				long timestmpLong=Long.parseLong(timestmp);
				long serverTimeLong=System.currentTimeMillis();
				if(Math.abs(serverTimeLong-timestmpLong)>timeDifference){
					error.setErrorMessage("用户认证失败，请确认您的系统时间是否正确");
					return null;
				}
			}
			return authentication(userName,ciphertext,timestmp,error);
		} catch (Throwable e) {
			error.setErrorMessage(e.getMessage());
			return null;
		}
	}
	
	private User authentication(String userName, String ciphertext,
		String timestmp,ServiceError error) throws Exception {
		User user = loadUser(userName,error);
		if(error.isError())return null;
		String password = user.getPassword();
		String md5Key = EncryptTools.MD5(password + timestmp);
		if (md5Key.length() > 16)
			md5Key = md5Key.substring(0, 16);
		String decodeTxt = EncryptTools.AESDecrypt(ciphertext, md5Key);
		if (decodeTxt != null && decodeTxt.equals(timestmp)) {
			user.setAuthorization(true);
			return user;
		} else {
			error.setErrorMessage("用户认证失败，请确认用户名密码是否输入正确");
			return null;
		}		
	}

	public User loadUser(String userName,ServiceError error) throws Exception {
		User user = null;
		String memcachedKey = "USER_MEMCACHED_UESERNAME_" + userName;
		try {
			String userJsonString = Application.getProvider().getCached(memcachedKey);
			if(userJsonString!=null)user = new User(userJsonString);
		} catch (Throwable e) {
			user = null;
		}
		if (user != null)return user;
		try {
			user = Application.getProvider().loadUser(userName);
			Application.getProvider().setCache(memcachedKey,USER_TIMEOUT, user.toString());			
			return user;
		} catch (Exception e) {
			error.setErrorMessage("用户加载失败,请确认用户名是否正确输入");
			return null;
		}
	}
}
